package org.example;

import java.awt.AWTException;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.awt.image.RescaleOp;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;

/**
 * java截屏
 * 运行后将当前屏幕截取，并最大化显示。
 * 拖拽鼠标，选择自己需要的部分。
 * 按Esc键保存图片到桌面，并退出程序。
 * 点击右上角（没有可见的按钮），退出程序，不保存图片。
 *
 * @author JinCeon
 */
class SnapshotTest {
    public static void main(String[] args) throws AWTException {
        // 全屏运行
        RectD rd = new RectD();
        GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment()
                .getDefaultScreenDevice();
        gd.setFullScreenWindow(rd);
    }
}

class RectD extends JFrame {
    private static final long serialVersionUID = 1L;
    int orgx, orgy, endx, endy;
    BufferedImage image;
    BufferedImage tempImage;
    BufferedImage saveImage;
    Graphics g;



    public RectD() throws AWTException {
        Robot robot = new Robot();
        image =  robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
        setAlwaysOnTop(true);
        setSize(image.getWidth(), image.getHeight());
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                orgx = e.getX();
                orgy = e.getY();
            }
            @Override
            public void mouseReleased(MouseEvent e) {
                try {
                    String format = "png";
                    File output = new File("screenshot.png");
                    ImageIO.write(saveImage, format, output);
                    System.out.println(e.getX()+ "  " + e.getY() + "  " +saveImage.getWidth() + "  " + saveImage.getHeight());
                    System.exit(0);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
        this.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                g = getGraphics();
                g.drawImage(tempImage, 0, 0, RectD.this);
                endx = e.getX();
                endy = e.getY();

                int x = Math.min(orgx, endx);
                int y = Math.min(orgy, endy);
                int width = Math.abs(endx - orgx)+1;
                int height = Math.abs(endy - orgy)+1;

                // 加上1，防止width或height为0
                g.setColor(Color.BLUE);
                g.drawRect(x-2, y-2, width+2, height+2);

                //减1，加1都是为了防止图片将矩形框覆盖掉
                saveImage = image.getSubimage(x, y, width, height);
                g.drawImage(saveImage, x, y, RectD.this);
            }
        });
        // 显示窗口
        setVisible(true);
    }

    @Override
    public void paint(Graphics g) {
        RescaleOp ro = new RescaleOp(0.5f, 0, null);
        tempImage = ro.filter(image, null);
        g.drawImage(tempImage, 0, 0, this);
    }

    public void saveToFile() {
        try {
            String format = "png";
            File output = new File("screenshot.png");
            ImageIO.write(saveImage, format, output);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}